﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using TimeBarPlugin.BarModel;
using Visiblox.Charts;

namespace TimeBarPlugin
{
	internal partial class DailyChart : UserControl
	{
		#region Attributes

		private IEnumerable<Bar> _bars;

		#endregion

		#region Properties

		public DataSeries<DateTime, decimal> BarValues { get; private set; }

		public DateTime Day
		{
			set
			{
				this.Chart.Title = value.Date.ToShortDateString();
			}
		}

		#endregion

		#region Public Methods

		public DailyChart()
		{
			this.BarValues = new DataSeries<DateTime, decimal>("Bar values");
			
			InitializeComponent();
		}

		public void Initialize(IEnumerable<Bar> bars, DateTime day, decimal minorTick)
		{
			_bars = bars;

			this.Day = day;
			this.YAxis.MinorTickInterval = (double)minorTick;
			this.GenerateData();
		}

		#endregion

		#region Private Methods

		private void GenerateData()
		{
			DailyChartPoints points = this.GenerateChartPoints();
			
			this.BarValues.AddRange(points.BarValues);

			this.Chart.Series[0].DataSeries = this.BarValues;
		}

		private DailyChartPoints GenerateChartPoints()
		{
			DailyChartPoints result = new DailyChartPoints();

			foreach (Bar bar in _bars)
			{
				Dictionary<object, decimal> data = new Dictionary<object, decimal>();
				data.Add(CandlestickSeries.High, bar.Maximum);
				data.Add(CandlestickSeries.Low, bar.Minimum);
				data.Add(CandlestickSeries.Open, bar.Open);
				data.Add(CandlestickSeries.Close, bar.Close);

				result.BarValues.Add(new MultiValuedDataPoint<DateTime, decimal>(bar.Start, data));
			}

			return result;
		}

		#endregion
	}
}
